package com.house.controller;

import com.house.utils.Code;
import com.house.utils.Result;
import org.springframework.stereotype.Controller;
import org.springframework.validation.FieldError;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.multipart.MultipartException;

import java.util.List;

/**
 * @author: GGP
 * @description: 全局异常处理类
 * @time: 2023-03-02 21:21
 **/
@RestControllerAdvice(annotations = {Controller.class, RestController.class})
public class GlobalExceptionHandler {

	/**
	 * 处理Hibernate Validator校验Bean参数抛出异常
	 */
	@ExceptionHandler(MethodArgumentNotValidException.class)
	public Result handlerMethodArgumentNotValidException(MethodArgumentNotValidException e) {
		List<ObjectError> allErrors = e.getBindingResult().getAllErrors();
		FieldError fieldError = (FieldError) allErrors.get(0);
		return new Result(Code.PARAMETER_ERR,fieldError.getDefaultMessage());
	}

	/**
	 * 文件上传过大异常捕获
	 * @param ex
	 * @return
	 */
	@ExceptionHandler(MultipartException.class)
	public Result handlerMaxUploadFile(MultipartException  ex) {
		return new Result(Code.SAVE_ERR,"上传内容过大");
	}

	/**
	 * 除了自定义的异常处理器，保留对Exception类型的异常处理，用于处理非预期的异常
	 * @param ex
	 * @return
	 */
	@ExceptionHandler(Exception.class)
	public Result doOtherException(Exception ex){
		ex.printStackTrace();
		return new Result(Code.SYSTEM_UN_KNOW_ERR,null,"系统繁忙，请稍后再试！");
	}


}
